import { defineStore } from "pinia";
import { loginApi, userInfoApi } from '@/api/user';
import { setToken, getToken, removeToken } from '@/utils/token';
// 
import { constantRoutes } from '@/router/routes';
import type { UserStatus } from "./type/type";




const useUserStore = defineStore('user', {

    // state: () => {
    state: (): UserStatus => {
        return {
            token: getToken() || '', // 从localStorage获取token
            menuRouteList: constantRoutes,
            userName: '',
            avatar: ''
        }
    },
    actions: {
        async login(loginForm: any) {
            const result = await loginApi(loginForm);
            this.token = result.token as string
            setToken(this.token);
            return 'ok'

            // if (result.code === 200) {
            //     this.token = result.token as string
            //     setToken(this.token);
            //     return 'ok'
            // } else {
            //     // return Promise.reject(new Error(result.data))
            //     return Promise.reject(result.msg)
            // }
        },

        async getUserInfo() {

            const result = await userInfoApi()

            // if (result.code !== 200) {
            //     return Promise.reject(result.data);
            // }

            // 实际应用中可能需要调用API获取用户信息
            this.userName = result.userName;
            this.avatar = result.avatar;
            return 'ok';
        },

        async logout() {
            this.token = '';
            this.userName = '';
            this.avatar = '';
            removeToken(); // 清除token
            // 这里可以添加其他登出逻辑，比如清除用户信息等
            return 'ok';
        }
    },
    getters: {}
})

export default useUserStore;

